import json
import os
from datetime import datetime
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from django.db.models import Q
from django.db import models
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.conf import settings
from qiniu import Auth, put_data

from .models import Order, OrderRating, CommentAuditLog
from .mongo_models import PendingComment
from .audit_chain import audit_chain
from .audit_worker import audit_worker
from .comment_serializers import (
    CommentSubmitSerializer, DriverCommentListSerializer,
    CommentAuditLogSerializer, CommentAuditStatusSerializer,
    AuditTaskStatusSerializer
)

class CommentSubmitView(APIView):
    """评论提交接口（支持文本和图片，集成七牛云上传）"""
    
    def post(self, request):
        """提交评论（支持图片上传到七牛云）"""
        serializer = CommentSubmitSerializer(data=request.data)
        
        if not serializer.is_valid():
            return Response({
                'code': 400,
                'message': '参数验证失败',
                'data': serializer.errors
            }, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            data = serializer.validated_data
            
            # 验证订单是否存在
            order = get_object_or_404(Order, id=data['order_id'])
            
            # 检查是否已经评价过
            existing_rating = OrderRating.objects.filter(
                order_id=data['order_id']
            ).first()
            
            if existing_rating:
                return Response({
                    'code': 400,
                    'message': '该订单已评价',
                    'data': None
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 处理图片上传到七牛云
            image_url = None
            if 'image' in request.FILES:
                image_file = request.FILES['image']
                
                try:
                    # 七牛云认证
                    q = Auth(settings.QINIU_ACCESS_KEY, settings.QINIU_SECRET_KEY)
                    
                    # 生成唯一的文件名
                    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
                    file_extension = os.path.splitext(image_file.name)[1]
                    key = f"comment_images/{data['order_id']}_{timestamp}{file_extension}"
                    
                    # 生成上传令牌
                    token = q.upload_token(settings.QINIU_BUCKET_NAME, key, 3600)
                    
                    # 上传到七牛云
                    ret, info = put_data(token, key, image_file.read())
                    
                    if info.status_code == 200:
                        image_url = f"{settings.QINIU_BUCKET_DOMAIN}/{key}"
                        print(f"图片已上传到七牛云: {image_url}")
                    else:
                        print(f"七牛云上传失败: {info}")
                        return Response({
                            'code': 500,
                            'message': '图片上传失败',
                            'data': None
                        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                        
                except Exception as e:
                    print(f"七牛云上传异常: {str(e)}")
                    return Response({
                        'code': 500,
                        'message': f'图片上传失败: {str(e)}',
                        'data': None
                    }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            
            # 创建MongoDB待审核评论
            pending_comment = PendingComment()
            comment_data = {
                'order_id': data['order_id'],
                'passenger_id': data['passenger_id'],
                'driver_id': data['driver_id'],
                'rating': data['rating'],
                'comment': data.get('comment', ''),
                'image_url': image_url,  # 保存七牛云图片URL
                'create_time': datetime.now(),
                'audit_status': 0  # 待审核
            }
            
            # 保存到MongoDB
            comment_id = pending_comment.create_comment(comment_data)
            
            if not comment_id:
                return Response({
                    'code': 500,
                    'message': '评论保存失败',
                    'data': None
                }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            
            # 添加到AI审核队列（包含图片URL）
            if data.get('comment') or image_url:
                audit_chain.add_audit_task(comment_id, data.get('comment', ''), image_url)
            
            # 注意：这里不创建MySQL记录，等AI审核通过后再创建
            # 只有审核通过的评论才会存入MySQL数据库
            
            return Response({
                'code': 200,
                'message': '评论提交成功，AI正在审核文本和图片',
                'data': {
                    'comment_id': comment_id,
                    'audit_status': 0,
                    'has_image': bool(image_url),
                    'image_url': image_url,
                    'estimated_time': '3-5分钟'  # AI审核预估时间
                }
            })
            
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'评论提交失败: {str(e)}',
                'data': None
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class CommentCRUDView(APIView):
    """评论增删改查接口"""
    
    def get(self, request, comment_id=None):
        """获取评论详情或列表"""
        if comment_id:
            # 获取单个评论详情
            try:
                # 先从MySQL查询
                comment = get_object_or_404(OrderRating, id=comment_id)
                serializer = DriverCommentListSerializer(comment)
                return Response({
                    'code': 200,
                    'message': '获取评论详情成功',
                    'data': serializer.data
                })
            except OrderRating.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '评论不存在',
                    'data': None
                }, status=status.HTTP_404_NOT_FOUND)
        else:
            # 获取评论列表（支持分页和筛选）
            page = int(request.query_params.get('page', 1))
            page_size = int(request.query_params.get('page_size', 20))
            driver_id = request.query_params.get('driver_id')
            passenger_id = request.query_params.get('passenger_id')
            audit_status = request.query_params.get('audit_status')
            
            queryset = OrderRating.objects.all()
            
            # 筛选条件
            if driver_id:
                queryset = queryset.filter(driver_id=driver_id)
            if passenger_id:
                queryset = queryset.filter(passenger_id=passenger_id)
            if audit_status is not None:
                queryset = queryset.filter(audit_status=int(audit_status))
            
            # 按时间倒序排列
            queryset = queryset.order_by('-rating_time')
            
            # 分页
            total = queryset.count()
            start = (page - 1) * page_size
            end = start + page_size
            comments = queryset[start:end]
            
            serializer = DriverCommentListSerializer(comments, many=True)
            
            return Response({
                'code': 200,
                'message': '获取评论列表成功',
                'data': {
                    'comments': serializer.data,
                    'pagination': {
                        'page': page,
                        'page_size': page_size,
                        'total': total
                    }
                }
            })
    
    def put(self, request, comment_id):
        """更新评论"""
        try:
            comment = get_object_or_404(OrderRating, id=comment_id)
            
            # 只允许更新评分、评论内容和图片URL
            rating = request.data.get('rating')
            comment_text = request.data.get('comment')
            image_url = request.data.get('image_url')
            
            if rating is not None:
                comment.rating = rating
            if comment_text is not None:
                comment.comment = comment_text
                # 如果更新了评论内容，需要重新进行AI审核
                comment.audit_status = 0  # 重置为待审核
                comment.audit_time = None
                comment.audit_result = None
                comment.is_sensitive = False
                
                # 添加到AI审核队列
                audit_chain.add_audit_task(str(comment_id), comment_text, image_url)
            if image_url is not None:
                comment.image_url = image_url
            
            comment.save()
            
            serializer = DriverCommentListSerializer(comment)
            return Response({
                'code': 200,
                'message': '评论更新成功',
                'data': serializer.data
            })
            
        except OrderRating.DoesNotExist:
            return Response({
                'code': 404,
                'message': '评论不存在',
                'data': None
            }, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'评论更新失败: {str(e)}',
                'data': None
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def delete(self, request, comment_id):
        """删除评论"""
        try:
            comment = get_object_or_404(OrderRating, id=comment_id)
            
            # 同时删除MongoDB中的评论
            pending_comment = PendingComment()
            pending_comment.delete_comment(str(comment_id))
            
            # 删除MySQL中的评论
            comment.delete()
            
            return Response({
                'code': 200,
                'message': '评论删除成功',
                'data': None
            })
            
        except OrderRating.DoesNotExist:
            return Response({
                'code': 404,
                'message': '评论不存在',
                'data': None
            }, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'评论删除失败: {str(e)}',
                'data': None
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class DriverCommentListView(APIView):
    """司机评论列表接口（只显示AI审核通过的评论）"""
    
    def get(self, request):
        """获取司机评论列表"""
        driver_id = request.query_params.get('driver_id')
        
        if not driver_id:
            return Response({
                'code': 400,
                'message': '缺少司机ID参数',
                'data': None
            }, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            # 获取该司机的所有评论（只显示AI审核通过的评论）
            comments = OrderRating.objects.filter(
                driver_id=driver_id,
                audit_status=1  # 只显示AI审核通过的评论
            ).order_by('-rating_time')
            
            serializer = DriverCommentListSerializer(comments, many=True)
            
            # 计算统计信息
            total_comments = comments.count()
            avg_rating = comments.aggregate(avg_rating=models.Avg('rating'))['avg_rating'] or 0
            
            return Response({
                'code': 200,
                'message': '获取评论列表成功',
                'data': {
                    'comments': serializer.data,
                    'statistics': {
                        'total_comments': total_comments,
                        'average_rating': round(float(avg_rating), 1),
                        'driver_id': driver_id
                    }
                }
            })
            
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'获取评论列表失败: {str(e)}',
                'data': None
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class CommentAuditStatusView(APIView):
    """评论审核状态查询接口"""
    
    def get(self, request):
        """查询评论审核状态"""
        comment_id = request.query_params.get('comment_id')
        
        if not comment_id:
            return Response({
                'code': 400,
                'message': '缺少评论ID参数',
                'data': None
            }, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            # 从Redis获取AI审核结果
            audit_result = audit_chain.get_audit_result(comment_id)
            
            if audit_result:
                return Response({
                    'code': 200,
                    'message': '获取AI审核状态成功',
                    'data': {
                        'comment_id': comment_id,
                        'audit_status': 1 if audit_result.get('audit_decision') == 'pass' else 2,
                        'audit_result': audit_result['reason'],
                        'sensitive_words': audit_result.get('sensitive_words', []),
                        'method': audit_result.get('method', 'unknown'),
                        'processing_time': audit_result.get('processing_time', 0),
                        'confidence': audit_result.get('confidence', 0),
                        'ai_decision': audit_result.get('audit_decision', 'pass'),
                        'text_audit': audit_result.get('text_audit'),
                        'image_audit': audit_result.get('image_audit')
                    }
                })
            else:
                # 从MongoDB查询
                pending_comment = PendingComment()
                comment_data = pending_comment.get_comment_by_id(comment_id)
                
                if comment_data:
                    return Response({
                        'code': 200,
                        'message': '获取AI审核状态成功',
                        'data': {
                            'comment_id': comment_id,
                            'audit_status': comment_data.get('audit_status', 0),
                            'audit_result': comment_data.get('audit_result', ''),
                            'sensitive_words': comment_data.get('sensitive_words', '').split(',') if comment_data.get('sensitive_words') else [],
                            'create_time': comment_data.get('create_time', '').isoformat() if comment_data.get('create_time') else None,
                            'has_image': bool(comment_data.get('image_url')),
                            'image_url': comment_data.get('image_url')
                        }
                    })
                else:
                    return Response({
                        'code': 404,
                        'message': '评论不存在',
                        'data': None
                    }, status=status.HTTP_404_NOT_FOUND)
                    
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'查询AI审核状态失败: {str(e)}',
                'data': None
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class AuditTaskStatusView(APIView):
    """AI审核任务状态接口"""
    
    def get(self, request):
        """获取AI审核任务状态"""
        try:
            pending_count = audit_worker.get_pending_count()
            worker_status = "running" if audit_worker.running else "stopped"
            
            return Response({
                'code': 200,
                'message': '获取AI审核任务状态成功',
                'data': {
                    'pending_count': pending_count,
                    'worker_status': worker_status,
                    'queue_name': settings.REDIS_TASK_CONFIG['task_queue']
                }
            })
            
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'获取AI审核任务状态失败: {str(e)}',
                'data': None
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def post(self, request):
        """启动/停止AI审核工作器"""
        action = request.data.get('action')
        
        if action == 'start':
            audit_worker.start()
            return Response({
                'code': 200,
                'message': 'AI审核工作器已启动',
                'data': None
            })
        elif action == 'stop':
            audit_worker.stop()
            return Response({
                'code': 200,
                'message': 'AI审核工作器已停止',
                'data': None
            })
        elif action == 'clear':
            audit_worker.clear_queue()
            return Response({
                'code': 200,
                'message': 'AI审核任务队列已清空',
                'data': None
            })
        else:
            return Response({
                'code': 400,
                'message': '无效的操作',
                'data': None
            }, status=status.HTTP_400_BAD_REQUEST)

class CommentAuditLogView(APIView):
    """评论AI审核日志接口"""
    
    def get(self, request):
        """获取AI审核日志列表"""
        try:
            # 支持分页和筛选
            page = int(request.query_params.get('page', 1))
            page_size = int(request.query_params.get('page_size', 20))
            audit_status = request.query_params.get('audit_status')
            
            queryset = CommentAuditLog.objects.all()
            
            # 按审核状态筛选
            if audit_status is not None:
                queryset = queryset.filter(audit_status=int(audit_status))
            
            # 按时间倒序排列
            queryset = queryset.order_by('-audit_time')
            
            # 分页
            start = (page - 1) * page_size
            end = start + page_size
            logs = queryset[start:end]
            
            serializer = CommentAuditLogSerializer(logs, many=True)
            
            return Response({
                'code': 200,
                'message': '获取AI审核日志成功',
                'data': {
                    'logs': serializer.data,
                    'pagination': {
                        'page': page,
                        'page_size': page_size,
                        'total': queryset.count()
                    }
                }
            })
            
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'获取AI审核日志失败: {str(e)}',
                'data': None
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class PendingCommentListView(APIView):
    """待审核评论列表接口"""
    
    def get(self, request):
        """获取待审核评论列表"""
        try:
            pending_comment = PendingComment()
            pending_comments = pending_comment.get_pending_comments()
            formatted_comments = []
            
            for comment in pending_comments:
                formatted_comment = {
                    '_id': str(comment['_id']),
                    'order_id': comment.get('order_id'),
                    'driver_id': comment.get('driver_id'),
                    'passenger_id': comment.get('passenger_id'),
                    'comment': comment.get('comment', ''),
                    'rating': comment.get('rating', 0),
                    'image_url': comment.get('image_url'),
                    'audit_status': comment.get('audit_status', 0),
                    'create_time': comment.get('create_time', '').isoformat() if comment.get('create_time') else None
                }
                formatted_comments.append(formatted_comment)
            
            return Response({
                'code': 200,
                'message': '获取待审核评论列表成功',
                'data': formatted_comments
            })
            
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'获取待审核评论列表失败: {str(e)}',
                'data': None
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)